package com.zaoke.web.service.food.impl;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.zaoke.web.bo.food.FoodImage;
import com.zaoke.web.dao.food.FoodImageDao;
import com.zaoke.web.service.food.FoodImageService;
import com.zaoke.web.utils.LocalCaches;

@SuppressWarnings("unchecked")
public class FoodImageServiceImpl implements FoodImageService{
	
	private FoodImageDao foodImageDao;
	
	private long expireTime;

	public FoodImage getImageByFoodId(long foodId) {
		Set<Long> foodIds = new HashSet<Long>();
		foodIds.add(foodId);
		Map<Long, FoodImage> images = getImageByFoodIds(foodIds);
		if(images != null && images.containsKey(foodId))
			return images.get(foodId);
		return null;
	}

	public Map<Long, FoodImage> getImageByFoodIds(Set<Long> ids) {
		Map<Long, FoodImage> result = new HashMap<Long, FoodImage>();
		
		List<FoodImage> images = getAllFoodImages();
		addImages(result, images, ids);

		Set<Long> remainings = new HashSet<Long>();
		for(Long id : ids)
			if(!result.containsKey(id))
				remainings.add(id);

		if(remainings.size() > 0){
			images = foodImageDao.getImagesByFoodIds(remainings,false);
			addImages(result, images, remainings);
		}
		
		return result;
	}

	private void addImages(Map<Long, FoodImage> result, List<FoodImage> images,
			Set<Long> remainings) {
		if(images != null && images.size() > 0)
			for(FoodImage image : images)
				if(image != null && remainings.contains(image.getFoodid()))
					result.put(image.getFoodid(), image);
	}

	private List<FoodImage> getAllFoodImages() {
		List<FoodImage> images = (List<FoodImage>)LocalCaches.get(LocalCaches.ZAOKE_CACHE_IMAGES_KEY, System.currentTimeMillis(), expireTime);
		
		if(images == null){
			images = foodImageDao.getAllImages();
			
			if(images != null && images.size() > 0)
				LocalCaches.set(LocalCaches.ZAOKE_CACHE_IMAGES_KEY, images, System.currentTimeMillis());
		}
		
		return images;
	}

	public long getExpireTime() {
		return expireTime;
	}

	public void setExpireTime(long expireTime) {
		this.expireTime = expireTime;
	}

	public FoodImageDao getFoodImageDao() {
		return foodImageDao;
	}

	public void setFoodImageDao(FoodImageDao foodImageDao) {
		this.foodImageDao = foodImageDao;
	}
}
